package hhpoll.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import org.hibernate.SessionFactory;
import hhpoll.dao.GenericDAO;


public abstract class GenericHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {

    protected SessionFactory sessionFactory;
    public Class<T> persistentClass;

    public GenericHibernateDAO(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                                .getGenericSuperclass()).getActualTypeArguments()[0];

    }

    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    @SuppressWarnings("unchecked")
    public T findByID (ID id) {
        return (T)this.sessionFactory.getCurrentSession().get(getPersistentClass(), id);
    }

    public T create (T t) {
    	// we need the semantics of merge as we don't want this particular 
    	// instance of T to be made persistent; we want a copy to be made.
    	// Note that this requires the IdTransferringMergeEventListener 
    	// to be configured, to get the id updated.
        this.sessionFactory.getCurrentSession().merge(t);
        //this.sessionFactory.getCurrentSession().save(t);
        //this.sessionFactory.flush();
        // Is id set here?
        return t;
    }

    public T update (T t) {
    	// we need the semantics of merge as we don't want this particular 
    	// instance of T to be made persistent; we want a copy to be made.
    	// Note that this requires the IdTransferringMergeEventListener 
    	// to be configured, to get the id updated.
        this.sessionFactory.getCurrentSession().merge(t);
        //this.sessionFactory.getCurrentSession().update(t);
        //this.sessionFactory.flush();
        // Is id set here?
        return t;
    }

    public void delete (ID id) {
        T t = this.findByID(id);
        this.sessionFactory.getCurrentSession().delete(t);
    }

}
